package com.hsource.doctorcenter.util;

import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.Bucket;
import com.aliyun.oss.model.OSSObject;
import com.aliyun.oss.model.ObjectMetadata;
import com.aliyun.oss.model.PutObjectResult;
import com.hsource.common.utils.DateUtil;
import com.hsource.doctorcenter.conf.oss.OssProperties;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.net.URL;
import java.util.Calendar;
import java.util.Date;

/**
 * @author yangYang
 * @version 1.0
 * @date 2020/10/9 9:23
 * @describe oss工具类
 */
@Component
@Slf4j
public class OSSUtil {
    //log
    private final Logger LOG = LoggerFactory.getLogger(OSSUtil.class);
    @Autowired
    public OssProperties ossProperties;
    /**
     * 获得url链接
     *
     * @param key
     * @return
     */
    public String getUrl(String key,OSSClient client) {
        // 设置URL过期时间为10年  3600l* 1000*24*365*10
        Date expiration = new Date(Calendar.getInstance().getTime().getTime() + 3600L * 1000 * 24 * 365 * 10);
        // 生成URL
        URL url = client.generatePresignedUrl(ossProperties.getBucketName(), key, expiration);
        if (url != null) {
            return url.toString();
        }
        return null;
    }

    /**
     * 获取阿里云OSS客户端对象
     * */
    public OSSClient getOSSClient(){
        return new OSSClient(ossProperties.getOssaddress(),ossProperties.getAccessKeyId(), ossProperties.getAccessKeySecret());
    }
    /**
     * 新建Bucket  --Bucket权限:私有
     * @param bucketName bucket名称
     * @return true 新建Bucket成功
     * */
    public boolean createBucket(OSSClient client, String bucketName){
        Bucket bucket = client.createBucket(bucketName);
        return bucketName.equals(bucket.getName());
    }
    /**
     * 删除Bucket
     * @param bucketName bucket名称
     * */
    public void deleteBucket(OSSClient client, String bucketName){
        client.deleteBucket(bucketName);
    }
    /**
     * 向阿里云的OSS存储中存储文件  --file也可以用InputStream替代
     * @param client OSS客户端
     * @param file 上传文件
     * @return String 唯一MD5数字签名
     * */
    public String uploadObject2OSS(OSSClient client, MultipartFile file) {
        URL url=null;
        String resultStr = null;
        try {
            InputStream is = file.getInputStream();
            String fileName = file.getOriginalFilename();
            //创建上传Object的Metadata
            ObjectMetadata metadata = new ObjectMetadata();
            metadata.setContentLength(is.available());
            metadata.setCacheControl("no-cache");
            metadata.setHeader("Pragma", "no-cache");
            metadata.setContentEncoding("utf-8");
            metadata.setContentType(getContentType(fileName));
            metadata.setContentDisposition("filename/filesize=" + fileName + is.available() + "Byte.");
            //上传文件
            String objectName = DateUtil.getStrFromDate(Calendar.getInstance().getTime(),"yyyyMMdd") + "/" + fileName;
            PutObjectResult putResult = client.putObject(ossProperties.getBucketName(), objectName, is, metadata);
            //解析结果
            //resultStr = putResult.getETag();
            is.close();
            Date expiration = new Date(Calendar.getInstance().getTime().getTime() + 3600L * 1000 * 24 * 365 * 10);
            url = client.generatePresignedUrl(ossProperties.getBucketName(), objectName, expiration);
            log.info(url.toString());
            return url.toString();
        } catch (Exception e) {
            LOG.error("上传阿里云OSS服务器异常." + e.getMessage(), e);
        }finally {
        }
        return null;
    }

    /**
     * 根据key获取OSS服务器上的文件输入流
     * @param client OSS客户端
     * @param bucketName bucket名称
     * @param filePath 文件路径
     * @param key Bucket下的文件的路径名+文件名
     */
    public InputStream getOSS2InputStream(OSSClient client, String bucketName, String filePath, String key){
        OSSObject ossObj = client.getObject(bucketName, filePath + key);
        return ossObj.getObjectContent();
    }

    /**
     * 根据key删除OSS服务器上的文件
     * @param client OSS客户端
     * @param bucketName bucket名称
     * @param filePath 文件路径
     * @param key Bucket下的文件的路径名+文件名
     */
    public void deleteFile(OSSClient client, String bucketName, String filePath, String key){
        client.deleteObject(bucketName, filePath+ key);
        LOG.info("删除" + bucketName + "下的文件" + filePath + key + "成功");
    }

    /**
     * 通过文件名判断并获取OSS服务文件上传时文件的contentType
     * @param fileName 文件名
     * @return 文件的contentType
     */
    public final String getContentType(String fileName){
        String fileExtension = fileName.substring(fileName.lastIndexOf(".")+1);
        if("bmp".equalsIgnoreCase(fileExtension)){
            return "image/bmp";
        }
        if("gif".equalsIgnoreCase(fileExtension)){
            return "image/gif";
        }
        if("jpeg".equalsIgnoreCase(fileExtension) || "jpg".equalsIgnoreCase(fileExtension)  ){
            return "image/jpg";
        }
        if("png".equalsIgnoreCase(fileExtension)){
            return "image/jpg";
        }
        if("html".equalsIgnoreCase(fileExtension)){
            return "text/html";
        }
        if("txt".equalsIgnoreCase(fileExtension)){
            return "text/plain";
        }
        if("vsd".equalsIgnoreCase(fileExtension)) {
            return "application/vnd.visio";
        }
        if("ppt".equalsIgnoreCase(fileExtension) || "pptx".equalsIgnoreCase(fileExtension)){
            return "application/vnd.ms-powerpoint";
        }
        if("doc".equalsIgnoreCase(fileExtension) || "docx".equalsIgnoreCase(fileExtension)){
            return "application/msword";
        }
        if("xml".equalsIgnoreCase(fileExtension)){
            return "text/xml";
        }
        if (fileName.toLowerCase().endsWith("mp3")) {
            return "audio/mp3";
        }
        if (fileName.toLowerCase().endsWith("mp4")) {
            return "video/mpeg4";
        }
        return "text/html";
    }

    /**
     * 销毁
     */
    public void destory(OSSClient client) {
        client.shutdown();
    }
}
